package com.neusoft.blog.config;


import com.neusoft.blog.bean.Menu;
import com.neusoft.blog.bean.Role;
import com.neusoft.blog.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 根据 请求路径 返回需要的 角色集合
 */
@Component
public class CommonsFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    MenuService menuService;
    AntPathMatcher antPathMatcher =new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        // 获取请求路径
        String requestURL =((FilterInvocation) o).getRequestUrl();
// 查询数据库，查询出 所有 路径与角色的关系
        List<Menu> menus = menuService.getAllMenes();

        for (Menu menu: menus) {
            if(antPathMatcher.match(menu.getPatten(),requestURL)){
                // 获取 需要的角色w
                List<Role> roleList=menu.getRoles();
                String str[]=new  String[roleList.size()];
                for (int i=0;i<str.length;i++){
                    str[i]="ROLE_"+roleList.get(i).getName();
                    System.out.println(str[i]);
                }
                return SecurityConfig.createList(str);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
